package com.itheima.service.impl;

import com.itheima.dao.UserDao;
import com.itheima.service.UserService;
import com.itheima.utils.MyTransactionManager;
import org.apache.commons.dbutils.DbUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    //注入数据源  目的是获取连接
    @Autowired
    private MyTransactionManager myTransactionManager;

    @Override
    public void transfer(String outName, String inName, Integer money) throws SQLException {
        System.out.println("转账方法执行了");

        //先获取一个连接
        // 在上面注入工具类 注入工具类

        //开启事务
        myTransactionManager.getConnection();

        try {

            //正常执行业务逻辑
            userDao.out(outName, money);
            //模拟死机的情况
            //int i = 1/0;

            userDao.in(inName, money);

            myTransactionManager.commitAndClose();

        } catch (Exception e) {
            e.printStackTrace();
            //如果出现异常 那么就进行回滚事务
            myTransactionManager.rollbackAndClose();
        }
    }
}
